<template>
  <div class="addPackageMaintenanceDLR">
    <FormPanel :isSubmitBtn="show" ref="packageFormpanel" :list="topFilterList" :cols="3" :labelWidth="125" :collapse="true" @formChange="changeHandle"></FormPanel>
    <div class="main-box">
      <div class="line">
        <div class="btn-box" v-if="packageType !== 'look'" :style="{ 'text-align':'right' }">
          <div>
            <el-button v-show="activeName1 === 'base'" type="text" icon="iconfont icon-add" @click="addFirst()">新增</el-button>
            <el-button v-show="activeName1 === 'car'" type="text" icon="iconfont icon-daoru" @click="downHandle"> 模板下载</el-button>
            <!-- <el-button v-show="activeName1 === 'car'" type="text" icon="iconfont icon-daoru" @click="addFirst()"> 导入</el-button> -->
             <ImportUploadFile  v-show="activeName1 === 'car'"
            style="margin: 0 10px"
            isOnlyButton
            :limit=100
            type="text"
            :dataSource="dataSource"
            :fileTypes="['xls', 'xlsx']"
            icon="iconfont icon-daoru"
            :actionUrl="actionUrl"
            @change="successHandler"

            >导入
          </ImportUploadFile>
            <el-button type="text" @click="handleDeleteFirst()"><em class="el-icon-delete" aria-hidden="true"></em> 删 除</el-button>
          </div>
        </div>
        <el-tabs v-model="activeName1" @tab-click="handleClick">
          <el-tab-pane label="基础规则" name="base">
            <baseRules ref="baseRules" />
          </el-tab-pane>
          <!-- <el-tab-pane label="车辆明细" name="car">
            <carDetail ref="carDetail" :carData='dataSource'/>
          </el-tab-pane> -->
        </el-tabs>

      </div>

      <div class="line">
          <div class="btn-box" v-if="packageType !== 'look'" :style="{ 'text-align':'right'  }">
          <div>
            <el-button type="text" icon="iconfont icon-add" @click="addSecond()">新 增</el-button>
            <el-button type="text" @click="handleDeleteSecond()"><em class="el-icon-delete"></em> 删 除</el-button>
          </div>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="维修工时" name="gs">
            <wxgs ref="wxgs" />
          </el-tab-pane>
          <el-tab-pane label="维修备件 " name="lj">
            <wxlj ref="packWxlj" />
          </el-tab-pane>
          <el-tab-pane label="附加项目" name="fj">
            <fjxm ref="fjxm" />
          </el-tab-pane>
        </el-tabs>

      </div>
    </div>
    <div class="bottom-line">
     <!-- <div class="amount">
        <div class="item">
          <span>工时费:</span> <em>{{ packageAllMoney.gs.toFixed(2) }}</em>
        </div>
        <div class="item">
          <span>备件费:</span> <em>{{ packageAllMoney.lj.toFixed(2) }}</em>
        </div>
        <div class="item">
          <span>附加费:</span> <em>{{ packageAllMoney.fj.toFixed(2) }}</em>
        </div>
        <div class="item">
          <span>总金额:</span> <em>{{ (packageAllMoney.gs + packageAllMoney.lj + packageAllMoney.fj).toFixed(2) }}</em>
        </div>
        <div class="item">
          <span>厂家奖励总金额:</span> <em>{{ ((packageAllMoney.jl||0)+(packageAllMoney.gl ||0)+(packageAllMoney.fl ||0)).toFixed(2) }}</em>
        </div>
      </div> -->
       <div class="btn" v-if="packageType !== 'look'">
        <el-button size="small" type="primary" @click="saveFn" class="btnStyle">保存</el-button>
        <el-button size="small" @click="saveFn('close')" class="btnStyle">取消</el-button>
      </div>
      <div class="btn" v-if="packageType === 'look'">
        <el-button size="small" @click="saveFn('close')" class="btnStyle">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { state, mutations } from './store';
import { dictionary } from '@/utils/dictMixin';
import { getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';//事业部，办事处
import { exportExcelFile } from '@/utils';

// import { saveActivity, queryActivityDetail, updateActivity } from '@/api-server/repair/repairReception/customer';

import { downCarTem,saveActivity,queryActivityDetail,updateActivity,getActivityCode } from '@/api/repair/repairBusiness/repairPackage';
import baseRules from './children/baseRules.vue';
import carDetail from './children/carDetail.vue';
import fjxm from './children/fjxm.vue';
import wxgs from './children/wxgs.vue';
import wxlj from './children/wxlj.vue';
import config from '@/assets/js/config';

// 组件
// import environmentalDetail from './environmentalDetail';

export default {
  name: 'environmentalInspection',
  mixins: [dictionary],
  props: {
    activityCode: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      show: false,
      activeName: 'gs',
      activeName1: 'base',
      topFilterList: this.createTopFilterList(),
      activityCodeValue: '',
      activityNameValue: '',
      actionUrl: `${config.uploadUrl}/api/dmscloud.activity/activity/uploadCarTem`,
      vinArr:[],
      dataSource:[],


      ORG_TYPE_SERVICE_BIG_AREA:15061020, //服务大区
      ORG_TYPE_SERVICE_SMALL_AREA:15061021, //服务小区
    };
  },
  components: { wxlj, wxgs, fjxm, carDetail, baseRules },
  computed: {
    packageType() {
      return state.packageType;
    },
    packageBaseRules() {
      return state.packageBaseRules;
    },
    packageCarDetail() {
      return state.packageCarDetail;
    },
    packageAllMoney() {
      return state.packageAllMoney;
    },
    packageWxgsList() {
      return state.packageWxgsList;
    },
    packageWxljList() {
      return state.packageWxljList;
    },
    packageAddItemList() {
      return state.packageAddItemList;
    }
  },
  watch: {},
  mounted() {

    this.getBigArea();
    console.log("this.packageType"+this.packageType)
    if (this.packageType !== 'add') {
      this.eiditData();

    }
    if (this.packageType == 'add') {

        // this.getCodeFun();
  }
  if (this.packageType == 'look') {
      this.topFilterList.forEach(x => {

        x.disabled = true;
      });
    }


  },
  methods: {

     //获取大，小区
    async getBigArea() {
      const res = await getLevelTwoAndThreeArea(15061020,null);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'serviceBigArea').itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
      }

      //   const res1 = await getLevelTwoAndThreeArea(15061021,null);
      // if (res1.resultCode === 200) {
      //   this.topFilterList.find(item => item.fieldName === 'serviceSmallArea').itemList = res1.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
      // }
    },
    // 获取套餐代码
    async getCodeFun() {
      const res = await getActivityCode({ 'ownerCode': '-1' });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'warning');
        } else {
          this.findFormItem('activityCode').initialValue = res.data;
          this.activityCodeValue = res.data;
        }
      }
    },
    // 取表单值通用方法
    findFormItem(fieldName) {
      return this.topFilterList.find(x => x.fieldName === fieldName) || {};
    },
    async eiditData() {
      console.log("this.activityCode"+this.activityCode)
      const res = await queryActivityDetail({ activityCode: this.activityCode });
      const nameList = ['startDate|endDate', 'startCrosstownDate|endCrosstownDate', 'activityType', 'isAllowDeleted','isParticipate','remark'];
      if (res.resultCode === 200) {
        this.topFilterList.forEach(x => {
          if (x.fieldName === 'startDate|endDate') {
            x.initialValue = [res.data.startDate, res.data.endDate];
          }
          if (x.fieldName === 'startCrosstownDate|endCrosstownDate') {
            x.initialValue = [res.data.startCrosstownDate ? res.data.startCrosstownDate : '', res.data.endCrosstownDate ? res.data.endCrosstownDate : ''];
          }
          if (x.fieldName === 'activityType') {
            x.initialValue = res.data['activityType'] ? res.data['activityType'] : null;
          }
          if (x.fieldName === 'isAllowDeleted') {
            x.initialValue = res.data['isAllowDeleted'];
          }
          if (x.fieldName === 'isParticipate') {
            x.initialValue = res.data['isParticipate'];
          }
           if (x.fieldName === 'remark') {
            x.initialValue = res.data['remark'];
          }
          if (!nameList.includes(x.fieldName)) {
            x.initialValue = res.data[x.fieldName] || res.data[x.fieldName] === 0 ? res.data[x.fieldName] + '' : null;
          }
        });
        this.activityCodeValue = res.data.activityCode;
        this.activityNameValue = res.data.activityName;
        console.log(this.topFilterList, res.data, 'eiditData==');
        mutations.setPackageBaseRules(res.data.activityBasicList);
        mutations.setPackageCarDetail(res.data.activityVehicleList);
        mutations.setPackageWxgsList(res.data.activityLabourList);
        mutations.setPackageWxljList(res.data.activityPartList);
        mutations.setPackageAddItemList(res.data.activityAddItemList);
        mutations.setAllMoney({ gs: res.data.labourAmount, lj: res.data.partAmount, fj: res.data.addItemAmount });
      }
    },

        /**
     * 根据数组对象的某个字段去重
     * item.name  是[{name:1}] 根据每条数据的name值来去重
     * */
    unique(arr, val) {
      const res = new Map();
      return arr.filter((item) => !res.has(item[val]) && res.set(item[val], 1));
    },
    successHandler(e) {
      console.log('e:::', e,this.vinArr);
      // debugger
      if (e != 1) {
        let obj = e[e.length - 1];
        let data = obj['url'];
        let successArr = data['success'];
        let newArr = [];
        console.log('successArr',successArr);
        newArr.push(...successArr);


         let vinArrs = this.unique(newArr, 'vin');

        if(newArr.length===0){
          newArr = successArr.concat(this.vinArr);
        }else{
          newArr = newArr.concat(this.vinArr);
        }

        let tempArr = this.unique(newArr, 'vin');
        this.newArr = tempArr;
        console.log('tempArr',tempArr)

        this.dataSource = tempArr;
        console.log('this.dataSource',this.dataSource)
        // this.$refs.carDetail.$refs.packageMaintenanceDLRCarDetail.DO_REFRESH();

        this.$notify.success({ title: '提示信息', message: '您共成功导入' + vinArrs.length + '条数据,如文档中存在重复vin次数取第一条' });
        this.$refs.carDetail.$refs.packageMaintenanceDLRCarDetail.$refs.pageTable.EXECUTE_INSERT(this.dataSource);
        mutations.setPackageCarDetail(this.dataSource);

      } else {
        if(e.errMsg=='当前excel为空，或检查下导入数据模板格式是否正确。'){
             this.$notify.error({ title: '提示信息', message: "请导入符合格式的数据" });
        }
      }

      this.UploadFileIsShow = false;
    },
   /*下载模板*/
    downHandle() {
      this.handleType = 'down';
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          downCarTem()
            .then((res) => {
              console.log(res, 'res');
              exportExcelFile(res.data, '车辆明细模板');
            })
            .catch((err) => {});
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },

    checkFn() {

      let modelList = [];
      for (const i of this.packageBaseRules) {
        if (!i.brand ) {
          this.$notify.warning({ title: '提示信息', message: `请填写基础规则信息！` });
          return;
        }
        if (i.model ) {
            modelList.push(i.model);
        }
      }

    for (const i of this.packageAddItemList) {

      if (!i.addItemAmount ) {
        this.$notify.warning({ title: '提示信息', message: `请填写附加项目必填项！` });
        return;
      }
      if(i.addItemAmount<0){
        this.$notify.warning({ title: '提示信息', message: `项目费不能小于0` });
          return;
        }
        if(i.addItemAmount.length>8){
        this.$notify.warning({ title: '提示信息', message: `项目费长度不能大于5` });
          return;
        }

    }

      for (const i of this.packageWxgsList) {
        console.log("modelList",modelList,"wgs",i.modelLabourCode,this.packageWxgsList)
        if (!modelList.includes(i.modelLabourCode)) {
          this.$notify.warning({ title: '提示信息', message: `与索赔工时单价维护的车型不匹配` });
          return;
        }

        if(i.stdLabourHour<0){
        this.$notify.warning({ title: '提示信息', message: `工时数不能小于0` });
          return;
        }
        if(i.stdLabourHour.length>8){
        this.$notify.warning({ title: '提示信息', message: `工时数长度不能大于5` });
          return;
        }

        if(i.labourPrice<0){
        this.$notify.warning({ title: '提示信息', message: `工时单价不能小于0` });
          return;
        }
        if(i.labourPrice.length>8){
        this.$notify.warning({ title: '提示信息', message: `工时单价长度不能大于5` });
          return;
        }
      }







  for (const i of this.packageWxljList) {
      if ((!i.partQuantity && i.partQuantity !== '0.00'  && i.relationLabourId ==="")) {
        this.$notify.warning({ title: '提示信息', message: `请填写备件必填项！` });
        console.log(this.packageWxljList, 'packageWxljList===');
        return;
      }

      if(i.relationLabourId===""){
        this.$notify.warning({ title: '提示信息', message: `请填写维修关联工时！` });
          return;
      }
      if(i.partSalesPrice<0){
        this.$notify.warning({ title: '提示信息', message: `备件单价不能小于0` });
          return;
        }
        if(i.partSalesPrice.length>8){
        this.$notify.warning({ title: '提示信息', message: `备件单价长度不能大于5` });
          return;
        }

        if(i.partQuantity<0){
        this.$notify.warning({ title: '提示信息', message: `备件数量不能小于0` });
          return;
        }
        if(i.partQuantity.length>8){
        this.$notify.warning({ title: '提示信息', message: `备件数量长度不能大于5` });
          return;
        }

    }



      return true;
    },
    async saveFn(n) {
      if (n === 'close') {
        this.$emit('close');
        return;
      }
      const obj = this.$refs.packageFormpanel.SUBMIT_FORM(); // 表单数据
      console.log(obj, 'formData==');

      if (!obj || !this.activityCodeValue || !this.activityNameValue ||  !obj.startDate || !obj.endDate) {
        this.$notify.warning({ title: '提示信息', message: '请填写必填项！' });
        console.log('formData==表单未必填');
        return;
      }

      if ((obj.minMileage === '0' && !obj.maxMileage && obj.maxMileage !== '0') || (!obj.minMileage && obj.maxMileage === '0' && obj.minMileage !== '0')) {
        this.$notify.warning({ title: '提示信息', message: '最小行驶里程和最大行驶里程请一起填写！' });
        return;
      }
      if ((obj.minMileage && !obj.maxMileage) || (!obj.minMileage && obj.maxMileage)) {
        this.$notify.warning({ title: '提示信息', message: '最小行驶里程和最大行驶里程请一起填写！' });
        return;
      }
      if (obj.minMileage && obj.maxMileage && Number(obj.maxMileage) < Number(obj.minMileage)) {
        this.$notify.warning({ title: '提示信息', message: '最大行驶里程不能小于最小行驶里程！' });
        return;
      }
      if (obj['startDate|endDate']) {
        obj.endDate = obj['startDate|endDate'][1];
      }
      if (obj['startCrosstownDate|endCrosstownDate']) {
        obj.endCrosstownDate = obj['startCrosstownDate|endCrosstownDate'][1];
      }
      console.log(obj, 'formData==');
      const tag = this.checkFn();
      if (!tag) {
        console.log('check--no');
        return;
      }

      console.log(obj, 'packageFormpanel==');
      console.log(this.packageBaseRules, 'packageBaseRules==');
      console.log(this.packageCarDetail, 'packageCarDetail--');
      console.log(this.packageWxgsList, 'packageWxgsList--');
      console.log(this.packageWxljList, 'packageWxljList--');
      console.log(this.packageAddItemList, 'packageAddItemList--');
      console.log(this.packageAllMoney, 'packageAllMoney--');


      // activityBasicList  activityVehicleList  activityLabourList    activityPartList ractivityAddItemList
      const params = JSON.parse(JSON.stringify(obj));
      if (params.startCrosstownDate) {
        params.endCrosstownDate = params['startCrosstownDate|endCrosstownDate'][1];
      }
      params.endDate = params['startDate|endDate'][1];
      params.activityBasicList = this.packageBaseRules;
      params.activityVehicleList = this.packageCarDetail;
      params.activityLabourList = this.packageWxgsList;
      params.activityPartList = this.packageWxljList;
      params.activityAddItemList = this.packageAddItemList;
      params.labourAmount = this.packageAllMoney.gs || 0;
      params.partAmount = this.packageAllMoney.lj || 0;
      params.addItemAmount = this.packageAllMoney.fj || 0;
      params.totalAmount = params.labourAmount + params.partAmount + params.addItemAmount;
      params.manufacturerAmount = ((this.packageAllMoney.jl||0) + (this.packageAllMoney.gl||0) + (this.packageAllMoney.fl||0) ).toFixed(2);
      params.activityCode = this.activityCodeValue;
      params.activityName = this.activityNameValue;
      for (const i in params) {
        if ((!params[i] && params[i] !== 0) || params[i] === '') {
          params[i] = null;
        }
      }

      console.log(params, 'params==');
      let res = null;
      if (this.packageType === 'edit') {
        res = await updateActivity(params);
      } else {
        res = await saveActivity(params);
      }

      if (res && res.resultCode === 200) {
        this.$notify({
          title: '提示信息',
          message: `${this.packageType === 'edit' ? '编辑成功' : '新增成功'}`,
          type: 'success'
        });
        this.$emit('close', 'success');
      }
    },

    addFirst() {
      console.log(this.activeName1, 'addFirst');
      switch (this.activeName1) {
        case 'base':
          this.$refs.baseRules.add();
          break;
        case 'car':
          this.$refs.carDetail.importHandle();
          break;
      }
    },
    addSecond() {
      console.log(this.activeName, 'addSecond');
      switch (this.activeName) {
        case 'gs':
          this.$refs.wxgs.add();
          break;
        case 'lj':
          this.$refs.packWxlj.add();
          break;
        case 'fj':
          this.$refs.fjxm.add();
          break;
      }
    },
    handleDeleteFirst() {
      console.log(this.activeName1, 'addFirst');
      switch (this.activeName1) {
        case 'base':
          this.$refs.baseRules.deleteClick();
          break;
        case 'car':
          this.$refs.carDetail.deleteClick();
          break;
      }
    },
    handleDeleteSecond() {
      console.log(this.activeName, 'handleDeleteSecond');
      switch (this.activeName) {
        case 'gs':
          this.$refs.wxgs.deleteClick();
          break;
        case 'lj':
          this.$refs.packWxlj.deleteClick();
          break;
        case 'fj':
          this.$refs.fjxm.deleteClick();
          break;
      }
    },
    handleClick() {
      console.log(this.activeName1, this.activeName, 'handleClick==');
      // this.activeName =
    },
    changeHandle() {
      // console.log(val, 'changeHandle==');
    },
    collapseHandle() {},
    closeDialog() {
      this.$emit('saveDialog');
    },
    activityCodeFn(n) {
      console.log(n, 'activityCodeFn');
      if (n === 1) {
        this.activityCodeValue = this.activityCodeValue.replace(/[\s\u4e00-\u9fa5_a-z`~!@#$%^&*()\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]/g, '');
        console.log(this.activityCodeValue);
        if (this.activityCodeValue) {
          this.topFilterList.find(x => x.fieldName === 'activityCode').initialValue = this.activityCodeValue;
        }
        return;
      } else {
        this.activityNameValue = this.activityNameValue.replace(/[\s`~!@#$%^&*()\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]/g, '');
        console.log(this.activityNameValue);
        if (this.activityNameValue) {
          this.topFilterList.find(x => x.fieldName === 'activityName').initialValue = this.activityNameValue;
        }
      }
    },
    activityNameFn() {},
    createTopFilterList() {
      return [
         {
          type: 'BREAK_SPACE',
          label: '基本信息',
        },
        {
          type: 'INPUT',
          label: '套餐代码',
          fieldName: 'activityCode',
          initialValue:'',
          rules: [{ required: true, message: '请填写套餐代码', trigger: 'change' }],
          render: () => {
            return <el-input  disabled={this.packageType !== 'add'}  v-model={this.activityCodeValue} onkeyup={this.activityCodeFn(1)} maxlength='10'></el-input>;
          }
        },
        {
          type: 'INPUT',
          label: '套餐名称',
          fieldName: 'activityName',
          rules: [{ required: true, message: '请填写套餐名称', trigger: 'change' }],
          render: () => {
            return <el-input disabled={this.packageType === 'look'} v-model={this.activityNameValue} onkeyup={this.activityCodeFn(2)} maxlength='100'></el-input>;
          }
        },

        {
          type: 'SELECT',
          label: '套餐类型',
          fieldName: 'activityType',
          initialValue: 56011001,
          rules: [{ required: true, message: '请选择套餐类型', trigger: 'change' }],
          itemList: this.createDictList('5601')
        },
        {
          type: 'SELECT',
          label: '套餐明细不可删除',
          fieldName: 'isAllowDeleted',
          initialValue: 10041001,
          rules: [{ required: true, message: '请选择是否可删除明细', trigger: 'change' }],
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '最小行驶里程',
          fieldName: 'minMileage',
          pattern: /^([0]|[1-9][0-9]*)$/,
          maxlength: 10,
          initialValue: '',

        },
        {
          type: 'INPUT',
          label: '最大行驶里程',
          fieldName: 'maxMileage',
          pattern: /^([0]|[1-9][0-9]*)$/,
          maxlength: 10,
          initialValue: '',

        },
        {
          type: 'RANGE_DATE',
          label: '开始/结束日期',
          fieldName: 'startDate|endDate',
          dateType: 'exactdaterange',
          initialValue: ['', ''],
          shortcuts: false,
          rules: [{ required: true, message: '请选择开始/结束日期', trigger: 'change' }]
        },

        {
          type: 'RANGE_DATE',
          label: '最早/最晚交车日期',
          fieldName: 'startCrosstownDate|endCrosstownDate',
          initialValue: ['', ''],
          dateType: 'exactdaterange',
          placeholder: ['最早交车日期', '最晚交车日期'],
          shortcuts: false
        },

        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入',
          rules: [{ required: false, trigger: 'change' }],
          initialValue: '',
          selfCols: 3,
          max:200
        },
      ];
    }
  }
};
</script>

<style lang="less" scoped>
.addPackageMaintenanceDLR {
  .main-box {
    margin-bottom: 50px;

    .line {
      position: relative;
      box-sizing: border-box;
      padding: 0 10px;
      // margin-bottom: 30px;
      // .btn-box {
      //   position: absolute;
      //   right: 30px;
      //   top: 5px;
      // }
      .table-wrapper {
        padding: 0;
      }
    }
  }
  .bottom-line {
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 9;
    border-top: 1px solid #e9e9e9;
    padding: 10px;
    background: #fff;
    text-align: right;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .amount {
      display: flex;
      box-sizing: border-box;
      font-weight: 500;
      .item {
        margin-right: 20px;
        span {
          margin-right: 5px;
        }
      }
    }
    .btn {
      display: flex;
    }
  }

}
</style>
